package com.app.baselibrary.delegate
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import com.app.baselibrary.BaseApplication
import com.scwang.smart.refresh.footer.BallPulseFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.properties.Delegates


/**
 * 代理类
 */
interface ApplicationDelegate {

    /**
     * 绑定[BaseApplication]
     */
    fun attachApplication(application: BaseApplication)


    /**
     * 当前代理类初始化
     */
    fun onDelegateCreate()


    /**
     * 获取[BaseApplication]
     */
    fun getApplication(): BaseApplication

    /**
     * 判断当前程序是否处于后台
     * @return true: 当前程序在后台运行，false：当前程序在前台运行
     */
    fun isAppBackground(): Boolean


    /**
     * 获取当前显示的activity
     */
    fun getTopActivity(): Activity?

    /**
     * 获取当前正在运行的ui
     */
    fun getAllActivity(): List<Activity>

    /**
     * 关闭所有Activity
     */
    fun finishAll()

    /**
     *关闭指定的Activity
     */
    fun finishActivity(activity: Activity, activityList: MutableList<Activity?>?)

    /**
     * 关闭指定类名的Activity
     */
    fun finishActivity(cls: Class<*>, activityList: MutableList<Activity?>?)
}

/**
 * 实现类
 */
 class  ApplicationDelegateImpl : ApplicationDelegate {

    companion object {

        var baseApplication: BaseApplication by Delegates.notNull()
            private set
    }

    private lateinit var mApplication: BaseApplication


    /**
     * 程序前后台状态
     */
    private val appBackground by lazy { AtomicBoolean(true) }


    /**
     * 当前正在显示的页面
     */
    private var mTopActivity: Activity? = null

    /**
     * 当前正在运行的所有ui
     */
    private val allActivity = LinkedList<Activity>()

    override fun attachApplication(application: BaseApplication) {
        baseApplication = application
        this.mApplication = application
    }

    override fun onDelegateCreate() {
        //初始化程序前后台状态观察类
        ProcessLifecycleOwner.get().lifecycle.addObserver(AppStatusObserver())
        //初始化刷新控件
        SmartRefreshLayout.setDefaultRefreshInitializer { context, layout ->
            layout.setRefreshHeader(MaterialHeader(context))
            layout.setRefreshFooter(BallPulseFooter(context))
        }
        mApplication.registerActivityLifecycleCallbacks(TopActivityCallback(this))
    }

    override fun getApplication(): BaseApplication {
        return this.mApplication
    }

    override fun isAppBackground(): Boolean {
        return appBackground.get()
    }


    override fun getTopActivity(): Activity? {
        return if (isAppBackground()) {
            null
        } else {
            mTopActivity
        }
    }


    override fun getAllActivity(): LinkedList<Activity> {
        return allActivity
    }


    override fun finishAll() {
        try {
            val iterator = getAllActivity().iterator()
            while (iterator.hasNext()){
                iterator.next().finish()
                iterator.remove()
            }
        } catch (e: Exception){
            e.printStackTrace()
        }
    }

    override fun finishActivity(activity: Activity, activityList: MutableList<Activity?>?) {
        if (activityList != null && activity != null && activityList.contains(activity)) {
            //使用迭代器安全删除
            val it: MutableIterator<Activity> = activityList.iterator() as MutableIterator<Activity>
            while (it.hasNext()) {
                val temp = it.next()
                // 清理掉已经释放的activity
                if (temp == null) {
                    it.remove()
                    continue
                }
                if (temp === activity) {
                    it.remove()
                }
            }
            activity.finish()
        }

    }

    override fun finishActivity(cls: Class<*>, activityList: MutableList<Activity?>?) {
        if (activityList != null) {
            // 使用迭代器安全删除
            val it = activityList.iterator()
            while (it.hasNext()) {
                val activity = it.next()
                // 清理掉已经释放的activity
                if (activity == null) {
                    it.remove()
                    continue
                }
                if (activity.javaClass == cls) {
                    it.remove()
                    activity.finish()
                }
            }
        }
    }


    inner class AppStatusObserver : DefaultLifecycleObserver {
        override fun onStart(owner: LifecycleOwner) {
            super.onStart(owner)
            appBackground.set(false)
        }

        override fun onStop(owner: LifecycleOwner) {
            super.onStop(owner)
            appBackground.set(true)
        }
    }


    inner class TopActivityCallback(private val impl: ApplicationDelegateImpl) : Application.ActivityLifecycleCallbacks {

        private var activityCount = 0

        override fun onActivityResumed(activity: Activity) {
            impl.mTopActivity = activity
        }

        override fun onActivityPaused(activity: Activity) {

        }
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            allActivity.addFirst(activity)
        }

        override fun onActivityDestroyed(activity: Activity) {
            val iterator = allActivity.iterator()
            while (iterator.hasNext()) {
                if (iterator.next() == activity) {
                    iterator.remove()
                }
            }
        }

        override fun onActivityStarted(activity: Activity) {
            activityCount++
            getAppStatus(activity)
        }


        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        }

        override fun onActivityStopped(activity: Activity) {
            activityCount--
            getAppStatus(activity)
        }
        /**
         * 根据activityCount,判断app状态
         */

        private fun getAppStatus(activity: Activity) {
            if (activityCount == 0) {
                //App进入后台或者APP锁屏了
            } else {
                //App进入前台清除通知
            }
        }
    }

}

/**
 *  代理方法
 */
fun applicationDelegate() = ApplicationDelegateImpl()